<template>
  <div>
    <el-dialog
      :title="mode == 'add' ? `创建${typeText}` : `编辑${typeText}`"
      width="660px"
      v-model="dialogFormVisible"
      :append-to-body="true"
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="rules" ref="formRef" class="form">
        <el-form-item
          label-width="120px"
          :label="`${typeText}名称`"
          prop="regionName"
        >
          <el-input
            placeholder="请输入"
            style="width: 360px; height: 36px"
            v-model="form.regionName"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item
          label-width="120px"
          label="上级层级"
          prop="subId"
        >
          <el-cascader
            ref="cascader"
            v-model="form.subId"
            :options="optionsRegionList"
            :props="{
              multiple: false,
              checkStrictly: true,
              label: 'regionName',
              value: 'id'
            }"
            clearable
            @change="changeCascader"
          ></el-cascader>
        </el-form-item>
        <el-form-item
          label-width="120px"
          :label="`${typeText}描述`"
          prop="regionRemark"
        >
          <el-input
            placeholder="请输入"
            v-model="form.regionRemark"
            type="textarea"
            :rows="3"
            style="width: 360px;"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">

import {REGION_CLASSIFY} from '@/constants/mapConstants'
import {createRegionApi, editRegionApi, regionInfoDTO} from "@/api/region";
import {CascaderValue, ElMessage, FormRules} from "element-plus";
export interface Props {
  mode: string,
  regionClassify: number,
  optionsRegion: Array<regionInfoDTO>
}

const props = withDefaults(defineProps<Props>(), {
  mode: 'add',
  regionClassify: 1,
  optionsRegion: () => []
})

const emit = defineEmits(['afterSubmit']);

const formRef = ref();

const typeText = ref<string>('层级');

const dialogFormVisible = ref<Boolean>(false)

const optionsRegionList = ref<Array<any>>()

const form = reactive<regionInfoDTO>({
  id: 0,
  regionName: '',
  subId: [0],
  regionRemark: '',
  parentId: 0,
})

const validRegionName = (rule: any, value: any, callback: Function) => {
  if (value == '') {
    callback(new Error(`请输入${typeText.value}名称`));
  } else if (value.length > 60) {
    callback(new Error('只能输入1~60个字符'));
  } else {
    callback();
  }
};

const validRegionRemark = (rule: any, value: any, callback: Function) => {
  if (value && value.length > 500) {
    callback(new Error('长度限制在500个字符'));
  } else {
    callback();
  }
};

const rules = reactive<FormRules<any>>({
  regionName: [{required: true, validator: validRegionName, trigger: 'change'}],
  subId: [{required: true, message: '请选择上级层级', trigger: 'change'}],
  regionRemark: [{validator: validRegionRemark, trigger: 'change'}]
})

const changeCascader = (val: Array<CascaderValue>) => {
  form.parentId = Number(val[val.length - 1]);
}

const submit = () => {
  if (!formRef) return
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      form.regionClassify = props.regionClassify
        let res;
      let text = "创建";
      if (props.mode == "add") {
        form.id = undefined
        res = await createRegionApi(form);
      } else {
        res = await editRegionApi(form);
        text = "编辑";
      }
      if (res.data.code == 0) {
        ElMessage.success(`${text}成功`)
        emit('afterSubmit')
        dialogFormVisible.value = false;
      }
    } else {
      return false
    }
  })
}

watch(() => props.regionClassify, (newVal) => {
  if (newVal == REGION_CLASSIFY['层级'].VALUE) typeText.value = '层级'
  if (newVal == REGION_CLASSIFY['区域'].VALUE) typeText.value = '区域'
})

watch(() => dialogFormVisible, (newVal) => {
  if(!newVal.value){
    Object.assign(form, {
      regionName: '',
      parentId: 0,
      regionRemark: '',
      regionClassify: 0,
      subId: [0],
      id: 0
    });
    formRef.value.resetFields();
  }
}, {deep: true});
watch(() => props.optionsRegion, (newVal) => {
  if(props.optionsRegion && props.optionsRegion[0].id != 0) {
    optionsRegionList.value = JSON.parse(JSON.stringify(props.optionsRegion));
    optionsRegionList?.value?.unshift({ regionName: '顶级', id: 0})
  }
})

defineExpose({
  dialogFormVisible,
  form
})

</script>

<style lang="scss" scoped>
:deep(.el-dialog__body) {
  padding: 20px;
  color: #606266;
  font-size: 14px;
  word-break: break-all;
  min-height: 340px;
  max-height: 340px;
  overflow: auto;
}
:deep(.el-cascader) {
  width: 360px;
}

</style>